package com.jcfy.common.utils.ip;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.fastjson.JSONObject;
import com.jcfy.common.utils.StringUtils;
import com.jcfy.common.utils.http.HttpUtils;
import com.jcfy.framework.config.JcfyConfig;

/**
 * 获取地址类
 *
 * @author jcfy
 */
public class AddressUtils {
    private static final Logger log = LoggerFactory.getLogger(AddressUtils.class);

    public static final String TENCENT_MAP_KEY = "WZNBZ-ZQB66-KD5SU-E2J6O-JRIBZ-LCFJP";

//    public static final String IP_URL = "http://ip.taobao.com/service/getIpInfo.php";
    public static final String IP_URL = "http://apis.map.qq.com/ws/location/v1/ip";

    public static String getRealAddressByIP(String ip) {
        String address = "XX XX";
        if (ip.contains(",")) {
            ip = ip.split(",")[0];
        }
        // 内网不查询
        if (IpUtils.internalIp(ip)) {
            return "内网IP";
        }
        if (JcfyConfig.isAddressEnabled()) {
//            String rspStr = HttpUtils.sendPost(IP_URL, "ip=" + ip);
            String rspStr = HttpUtils.sendGet(IP_URL, "ip=" + ip + "&key=" + TENCENT_MAP_KEY);
            if (StringUtils.isEmpty(rspStr)) {
                log.error("获取地理位置异常 {}", ip);
                return address;
            }
//            JSONObject obj = JSONObject.parseObject(rspStr);
//            JSONObject data = obj.getObject("data", JSONObject.class);
//            String region = data.getString("region");
//            String city = data.getString("city");
//            address = region + " " + city;
            JSONObject obj = JSONObject.parseObject(rspStr);
            JSONObject result = obj.getObject("result", JSONObject.class);
            JSONObject data = result.getObject("ad_info", JSONObject.class);
            String province = data.getString("province");
            String city = data.getString("city");
            address = province + " " + city;
        }
        return address;
    }
}
